import { Effect } from 'dva-core-ts';
import {Reducer} from 'redux';
import { UserServices } from '../../services/type';
import { IUserLoginResponse } from '../../services/user/type';
export interface IUserModelState{
    isLogin: boolean
  userInfo: {
    username: string
    login_token: string
    avatarSrc?: string
  } | null
}
export interface IUserModel {
  namespace: 'user'
  state: IUserModelState
  reducers: {
    login: Reducer<IUserModelState>
  }
  effects:{
    loginEffect: Effect
  }
}

const userModel : IUserModel = {
    namespace:"user",
    state:{
        isLogin: false,
        userInfo: {
            username:"我的",
            login_token:'',
    }},
    reducers: {
   login(state, action) {
      console.log("login"+action?.payload?.username)
      return {
        ...state,
        isLogin: true,
        userInfo: {
          username: action?.payload?.username,
          login_token: action?.payload?.token,
          avatarSrc: action?.payload?.userInfo?.avatarSrc
        }
      }
    },
    },
    effects:{
      *loginEffect({ payload, callback }, { call, put }) {
      // 执行异步函数
      const res: IUserLoginResponse = yield call(() => UserServices.login(payload))
      if (res) {
        callback && callback(res)
        yield put({
          type: 'login',
          payload: res
        })
      }
    },
    }  
}
export default userModel;